package cn.hist.hfp.service;

import cn.hist.hfp.converter.BusinessConverter;
import cn.hist.hfp.entity.Business;
import cn.hist.hfp.exception.ResourceNotFoundException;
import cn.hist.hfp.repository.BusinessRepository;
import cn.hist.hfp.vo.BusinessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BusinessService {

    private final
    BusinessRepository businessRepository;

    private final BusinessConverter businessConverter;

    @Autowired
    public BusinessService(BusinessRepository businessRepository, BusinessConverter businessConverter) {
        this.businessRepository = businessRepository;
        this.businessConverter = businessConverter;
    }

    public Business create(Business business) {
        return businessRepository.save(business);
    }

    public Business findOne(int id) {
        Optional<Business> optionalBusiness = businessRepository.findById(id);
        if (optionalBusiness.isPresent()) {
            return optionalBusiness.get();
        }
        throw new ResourceNotFoundException();
    }

    public List<BusinessVO> findAll() {
        return businessConverter.convert(businessRepository.findAll());
    }

    public Business update(Business business) {
        return businessRepository.save(business);
    }

    public int delete(int id) {
        Optional<Business> optionalBusiness = businessRepository.findById(id);
        optionalBusiness.ifPresent(businessRepository::delete);
        return businessRepository.findById(id).isPresent() ? 0 : 1;
    }
}
